package com.aaa.security;

import com.aaa.entity.Emp;
import com.aaa.entity.EmpT;
import com.aaa.entity.ResponseMsg;
import com.aaa.jwt.JwtTokenUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/*
* 认证成功处理器:登录成功
* */
@Component
public class SuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {


        //响应设置
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setHeader("Content-type","application/json");
        httpServletResponse.setStatus(200);
       // ResponseMsg responseMsg=new ResponseMsg(200,"认证成功",principal);
       String token= JwtTokenUtils.getToken(authentication);
        Emp principal = (Emp) authentication.getPrincipal();//用户信息
        Map<String,Object> str=new HashMap<>();
        str.put("token",token);
        str.put("principal",principal);
        str.put("photo",principal.getPhoto());
        str.put("authstate",principal.getAuthstate());
        ResponseMsg msg=new ResponseMsg();
        msg.setCode(200);
        msg.setMsg("认证成功");
        msg.setData(str);
        //FastJSPN
        //写:字符输出流
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write(JSONObject.toJSONString(msg));
        writer.flush();
        writer.close();

    }
}
